package com.zhangxiaofanfan.hotcode.third;

import org.junit.platform.commons.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-100-liked">无重复字符的最长子串</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-22 22:29:36
 */
public class HotCode008 {
    public static void main(String[] args) {
        String s = "abba";
        HotCode008 hotCode008 = new HotCode008();
        System.out.println(hotCode008.lengthOfLongestSubstring(s));
    }

    public int lengthOfLongestSubstring(String s) {
        if (StringUtils.isBlank(s)) {
            return 0;
        }
        int left = 0;
        int right = 0;
        int maxLen = 0;
        Map<Character, Integer> map = new HashMap<>();
        while (right < s.length()) {
            if (map.containsKey(s.charAt(right))) {
                left = map.get(s.charAt(right)) + 1;
                map.put(s.charAt(right), right);
            } else {
                map.put(s.charAt(right), right);
            }
            maxLen = Math.max(maxLen, right - left + 1);
            right++;
        }
        return maxLen;
    }
}
